var https = require('https');
var images = require('images');
var path = require('path');
var qr = require('qr-image');
const { Add, Update, QueryOne } = require('../db/dbhelper');
var { init, format } = require('../models/qrcode');

//新增
const qrcodeAdd = function (doc) {
  return Add('hzz_qrcodes', init(doc));
}

//修改
const qrcodeUpdate = function (doc) {
  return Update('hzz_qrcodes', format(doc));
}

const qrcodeQueryOne = function (doc, select) {
  return QueryOne('hzz_qrcodes', doc, select);
}

async function buildQrcode(url) {
  try {
    const margin = 365; // 二维码的左右边距
    const top = 960; // 二维码距顶部的距离
    var sourceImage = images(path.join(__dirname, '../../files/report.jpg'));
    var w = sourceImage.width(); // 模板图片的宽度
    var h = sourceImage.height(); // 模板图片的宽度
    var qrImage = images(qr.imageSync(url, { type: 'png' })).size(w - 515); // 二维码的尺寸为：模板图片的宽度减去左右边距
    return sourceImage
      .draw(qrImage, margin, top) // 二维码的位置：x=左边距，y=top
      .encode('png', { quality: 90 });
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  qrcodeAdd,
  qrcodeUpdate,
  qrcodeQueryOne,
  buildQrcode
}